/**
 ************************************************************************
  > File Name: controllers/admin.js
  > Author: Leeiio <iio@iiobox.com>
  > Site: https://www.iiobox.com
  > Created Time: 08/04/17 17:26:30
 ************************************************************************/

var validator = require('validator');
var Eventproxy = require('eventproxy');
var User = require('../proxy').User;
var models = require('../models');
var tools = require('../common/tools');
var logger = require('../common/logger');

// dashboard页面
exports.dashboard = function dashboard(req, res, next) {
  var ep = new Eventproxy();
  ep.fail(next);

  ep.all('end', function(end) {
    return res.render('dashboard', {
      user: user,
      end: end
    });
  });

  var user = req.session.user;

  ep.emit('end', user);
};


// 账户页面
exports.account = function account(req, res) {
  return res.render('account');
};

// change password
exports.change_password = function (req, res, next) {
  var ep = new Eventproxy();
  ep.fail(next);
  ep.on('prop_err', function (msg) {
    res.send_data({
      code: 422,
      message: msg
    });
  });
  var oldPass = validator.trim(req.body.old_pass);
  var newPass = validator.trim(req.body.new_pass);
  var retryNewPass = validator.trim(req.body.new_pass);
  if (newPass !== retryNewPass) {
    return ep.emit('prop_err', '新密码两次输入不一致');
  }
  if (!oldPass || !newPass) {
    return ep.emit('prop_err', '旧密码或新密码不得为空');
  }

  var userUUID = req.session.user.uuid;
  User.findByUUID(userUUID).then(function (user) {
    tools.bcompare(oldPass, user.pass, ep.done(function (bool) {
      if (!bool) {
        return ep.emit('prop_err', '当前密码不正确');
      }

      tools.bhash(newPass, ep.done(function (passhash) {
        user.update({
          pass: passhash
        }).then(function () {
          return res.send_data({
            code: 200,
            message: '密码已修改成功'
          });
        }).catch(function (err) {
          logger.error(err);
          return next(err);
        });
      }));
    }));
  });
};

